<?php
/**
 * 采购需求汇总 及相关
 */
class procsumController extends baseController
{
	/**
	 * 待汇总需求
	 * todo: 提交保存到save()之前，是否需要预览一下
	 */
	public function show(){
		$list = ProcSumHelper::getRequests();
		$this->assign('list', $list);
		$this->display();
	}

	/** 保存汇总 */
	public function save(){
		$array = fetch_a_array('demand'); //demand_ids
		if(!$array){
			Show::warn('请选择采购需求');
		}

		$sno_l  = array();
		$amount = 0;
		foreach($array as $id){
			$demand = Demand::get($id);
			if(!$demand){
				Show::warn('部分采购需求不存在', url('procsum'));
			}
			$sno_l[] = $demand['sno'];
			$amount += $demand['amount'];
		}

		Db::get()->trans()->on();
		//创建汇总记录
		$summary_id = Summary::add(array(
			'addtime'	=> time(),
			'user_id'	=> UID,
			'demands'	=> join(', ', $sno_l),
			'amount'	=> $amount,
			'remainder'	=> $amount,
			'flow'		=> 0,
		));
		if(!$summary_id){
			Show::warn('保存失败1');
		}
		//修改需求表，设置汇总记录 summary_id
		foreach($array as $id){
			if(!Demand::update($id, array('summary_id'=>$summary_id))){
				Db::get()->trans()->rollback();
				Show::warn('保存失败2');
			}
		}
		//修改需求材料表的状态state，置为已汇总
		$r = Db::get('DemandItems')->update(array('state'=>DemandItems::STATE_SUMMARY))
							->where(array('demand_id','IN',$array))->exec();
		if(!$r){
			Db::get()->trans()->rollback();
			Show::warn('保存失败3');
		}

		Db::get()->trans()->commit();

		Show::ajaxBand(array('summary_id'=>$summary_id));
		Show::note('操作成功');
	}

	/** 查看汇总 */
	public function view(){
		$summary_id = fetch_a_int('id');
		$summary = Summary::get($summary_id);
		if(!$summary){
			Show::warn('此采购需求汇总记录不存在');
		}
//		Debug::pre(SummaryItemsHelper::getBySummary($summary_id));
		$summary['items'] = SummaryItemsHelper::splitbyDemandType(SummaryItemsHelper::getBySummary($summary_id));
//		Debug::pre($summary['items']);
		$this->assign('summary', $summary);
		$this->display();
	}

	/** 列表汇总 */
	public function hist(){
		$where = array();
		$where[] = str_replace('addtime','t0.addtime',Lib::makeTimesRange());
                $_where = join(' AND ',$where);
                $_list = SummaryHelper::getList($_where, 0, null);
                $keys = array();
                foreach($_list as $k=>$v)
                {
                    $_v = explode(',', $v['demands']);
                    foreach($_v as $val)
                    {
                        $keys[trim($val)] = trim($val);
                    }
                }
                
                $demands = fetch_a_string('demands');
                if($demands)
                {
                    $where[] = "demands LIKE  '%{$demands}%'";
                }
		$where = join(' AND ',$where);
		
		$limit = PagerHelper::split2limit(SummaryHelper::getCount($where));
		$list = SummaryHelper::getList($where, $limit[0], $limit[1]);
                
                $this->assign('demands',$keys);
		$this->assign('list', $list);
		$this->display();
	}

	/** 待报价列表 */
	public function quote(){
		$where = array();
		$where[] = str_replace('addtime', 't0.addtime', Lib::makeTimesRange());
		$where = join(' AND ', $where);
		$count = SummaryHelper::getCount($where);
		$limit = PagerHelper::split2limit($count);
		$list = SummaryHelper::getList($where, $limit[0], $limit[1]);
//		Debug::pre($list);
		$this->assign('list', $list);
		$this->display();
	}

	/**
	 * 比价选择
	 */
	public function elect()
	{
		$id	= fetch_a_int('id');
		if(!$id){
			$this->redirect('procsum-quote');
		}

		$wares = SummaryHelper::getWares($id, 1);
                
		if(!$wares){
			//todo: 采购汇总，无法判断是否全部输入价格
//			$this->redirect('procsum-quote');
			Show::warn('需求材料的报价已录入完毕');
		}
		
		$this->assign('summary', Summary::get($id));

		$stids	= array();
		$spids	= array();
		$stuffs	= array();
		foreach($wares as $s)
		{
			$stuffs[$s['ware_id']]	= array_merge($s, array('suppliers'=>array()));
			$stids[] = $s['ware_id'];
			if($s['supplier_id'])
				$spids[] = $s['supplier_id'];
		}

		//取供应商列表，支持指定供应商
		$where	= '1';
		$limit	= 3;
		if(fetch_a_string('spids'))
		{
			$tmp	= array_map("intval", explode(',', fetch_a_string('spids')));
			$where	.= sprintf(' AND id IN (%s)', join(',', $tmp));
			$limit	= count($tmp);
		}
		elseif($spids)
		{
			$spids	= array_unique($spids);
			$where	.= sprintf(' AND id IN (%s)', join(',', $spids));
			$limit	= null;
		}

		$sprs	= Supplier::getList($where, 0, $limit);
		$spids	= array_keys($sprs);

		//同步取供应商材料报价
		$costs	= Db::get('SupplierQuote')->select()->where(array('supplier_id','IN',$spids), array('ware_id','IN',$stids))->getAll();
		foreach($costs as $c)
		{
			$stuffs[$c['ware_id']]['suppliers'][$c['supplier_id']]	= $c;
		}
                
                foreach($stuffs as $k=>$v)
                {
                    $tmp = Db::get('_DemandItems')->select('quote_remark')->where(array('ware_id'=>$v['ware_id']))->getOne();
                    $stuffs[$k]['quote_remark'] = $tmp['quote_remark'];
                }

//		$stuffs	= $this->stuffclsfilter($stuffs);

//		Debug::pre($stuffs);
		$this->assign('stuffs',		$stuffs);
		$this->assign('suppliers',	$sprs);
		$this->assign('all_suppliers',	Supplier::getList());
		$this->display();
	}

	/**
	 * 保存比价结果
	 */
	public function do_elect()
	{
		$id	= fetch_a_int('summary_id');
		if(!$id){
			Show::warn('参数错误');
		}

		$summary = Summary::get($id);
		if(!$summary){
			Show::warn('无此需求汇总');
		}
		if($summary['flow']!=0){
			Show::warn('此需求汇总已全部生成订单');
		}

		$wares = SummaryHelper::getWares($id);
		if(!$wares){
			Show::warn('需求汇总未找到或无待采内容');
		}

		if(empty($_POST['spid'])){
			Show::warn('请选择材料供应商');
		}
		if(empty($_POST['remark'])) $_POST['remark'] = array();

		$tmp = array();
		foreach($_POST['spid'] as $ware_id=>$supplier_id){
			if(isset($wares[$ware_id]) && intval($supplier_id)){
				$tmp[$ware_id] = array( intval($supplier_id),
										$wares[$ware_id]['amount'],
										0.0, //保留价格位,由quoteWare使用
										fetch_a_string($ware_id, $_POST['remark']) );
			}
		}
		SummaryHelper::quoteWares($id, $tmp);
		Summary::update($id, array('spids'=>join(',',fetch_a_array('sspid'))));

		Show::note('保存成功', url('procsum-elect/id/'.$id));
	}


}

?>
